package com.elegantmall.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.elegantmall.annotation.NeedAuth;
import com.elegantmall.service.AdminServiceImpl;
import com.elegantmall.service.SellerServiceImpl;
import com.elegantmall.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginController {

    @Autowired
    private AdminServiceImpl adminService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private SellerServiceImpl sellerService;


    @RequestMapping(value = "/login", method= RequestMethod.POST)
    public String dologin(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("role") String role) {

        // 根据角色调用不同服务
        switch (role) {
            case "admin":
                if(adminService.login(username,password)){

                    StpUtil.login(username);
                    return SaResult.ok("登录成功").toString();
                }
                else{
                    return SaResult.error("登录失败").toString();
                }

            case "user":
                if(userService.login(username,password)){

                    StpUtil.login(username);
                    return SaResult.ok("登录成功").toString();
                }
                else{
                    return SaResult.error("登录失败").toString();
                }

            case "seller":

                if(sellerService.login(username,password)){

                    StpUtil.login(username);
                    return SaResult.ok("登录成功").toString();
                }
                else{
                    return SaResult.error("登录失败").toString();
                }
            default:
                return "no";
        }
    }

    @PostMapping("/register")
    public SaResult doregister(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("nickname") String nickname,
            @RequestParam("role") String role
    ){
        switch (role) {
            case "user":
                return userService.register(username, password, nickname);
            case "seller":
                return sellerService.register(username, password, nickname);
            default:
                return SaResult.error("非法的用户角色");
        }

    }

    @NeedAuth
    @RequestMapping(value = "/testhello", method= RequestMethod.GET)
    public String dotesthello() {
        System.out.println("hello,you are authed");
        return "hello";
    }
}
